package com.hj.system.system.controller;

import com.hj.system.base.annotation.SystemLog;
import com.hj.system.base.utils.MD5Utils;
import com.hj.system.base.utils.PageUtils;
import com.hj.system.common.controller.BaseController;
import com.hj.system.common.service.DictService;
import com.hj.system.base.utils.ResponseUtil;
import com.hj.system.system.config.SystemProperties;
import com.hj.system.system.domain.RoleDO;
import com.hj.system.system.domain.UserDO;
import com.hj.system.system.service.RoleService;
import com.hj.system.system.service.UserService;
import com.hj.system.system.vo.UserVO;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    private String prefix = "system/user";
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DictService dictService;
    @Autowired
    private SystemProperties properties;

    @RequiresPermissions("sys:user:user")
    @GetMapping
    public String user() {
        return prefix + "/user";
    }

    /**
     * 分页 查询列表数据
     */
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtils = userService.list(params);
        return ResponseUtil.okContent(pageUtils);
    }

    @RequiresPermissions(value = {"sys:user:add", "sys:user:edit"}, logical = Logical.OR)
    @GetMapping("/modify")
    public String modify(String userId, Model model, String deptId) {
        UserDO userDO;
        if (userId != null && !"".equalsIgnoreCase(userId)) {
            userDO = userService.get(userId);
        } else {
            userDO = new UserDO();
            userDO.setDeptId(deptId);
        }
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.listUserRoles(userId);
        model.addAttribute("roles", roles);
        return prefix + "/modify";
    }

    @RequiresPermissions("sys:user:add")
    @SystemLog("保存用户")
    @PostMapping("/save")
    @ResponseBody
    public ResponseUtil save(UserDO user) {
        user.setPassword(MD5Utils.encrypt(user.getUsername(), properties.getResetPw()));
        if (userService.save(user) > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }

    @RequiresPermissions("sys:user:edit")
    @SystemLog("更新用户")
    @PostMapping("/update")
    @ResponseBody
    public ResponseUtil update(UserDO user) {
        if (userService.update(user) > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }


    @RequiresPermissions("sys:user:edit")
    @SystemLog("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    public ResponseUtil updatePeronal(UserDO user) {
        if (userService.updatePersonal(user) > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }


    @RequiresPermissions("sys:user:remove")
    @SystemLog("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    public ResponseUtil remove(String userId) {
        if (userService.remove(userId) > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }

    @RequiresPermissions("sys:user:batchRemove")
    @SystemLog("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    public ResponseUtil batchRemove(@RequestParam("ids[]") String[] userIds) {
        int r = userService.batchRemove(userIds);
        if (r > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }

    @PostMapping("/exit")
    @ResponseBody
    public boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }


    @SystemLog("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    public ResponseUtil resetPwd(UserVO userVO) {
        try {
            userService.resetPwd(userVO, getUser());
            return ResponseUtil.ok();
        } catch (Exception e) {
            return ResponseUtil.error(1, e.getMessage());
        }
    }

    @RequiresPermissions("sys:user:resetPwd")
    @SystemLog("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    public ResponseUtil adminResetPwd(UserVO userVO) {
        try {
            userVO.setPwdNew(properties.getResetPw());
            userService.adminResetPwd(userVO);
            return ResponseUtil.ok();
        } catch (Exception e) {
            return ResponseUtil.error(1, e.getMessage());
        }

    }


    @GetMapping("/personal")
    public String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        if (userDO.getBirth() == null) {
            userDO.setBirth(new Date());
        }
        model.addAttribute("user", userDO);
        model.addAttribute("hobbyList", dictService.listByType("hobby"));
        return prefix + "/personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    public ResponseUtil uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        Map<String, Object> result;
        try {
            result = userService.updatePersonalImg(file, avatar_data, String.valueOf(getUserId()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return ResponseUtil.ok(result);
        } else {
            return ResponseUtil.error("更新图像失败！");
        }
    }
}
